package com.xu.cloud.auth.component.oauth;

import com.xu.cloud.auth.enums.ThirdPartyEnum;
import com.xu.cloud.auth.exception.AuthErrorCodeEnum;
import com.xu.cloud.auth.pojo.bo.OAuth2AccessTokenBO;
import com.xu.cloud.auth.pojo.bo.OAuth2UserInfo;
import com.xu.cloud.common.util.AssertUtil;
import com.xu.cloud.common.util.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xuguan
 * @since 2025/2/27
 */
@Component
public class OAuth2ExecutionChain {

    @Autowired
    private List<IOAuth2> IOAuth2s;

    public IOAuth2 checkOAuth2Component(ThirdPartyEnum thirdPartyEnum) {
        final IOAuth2 select = select(thirdPartyEnum);
        AssertUtil.assertNotNull(select,
                AuthErrorCodeEnum.THIRD_PARTY_LOGIN_NOT_SUPPORT.info().newException());
        return select;
    }

    @NonNull
    public OAuth2UserInfo oauth2UserInfo(ThirdPartyEnum thirdPartyEnum, String code) {
        final IOAuth2 oauth2 = checkOAuth2Component(thirdPartyEnum);
        final OAuth2UserInfo oAuth2UserInfo;
        try {
            final OAuth2AccessTokenBO accessTokenBo = oauth2.getAccessToken(code);
            oAuth2UserInfo = oauth2.oauth2UserInfo(accessTokenBo);
        } catch (Exception e) {
            throw ExceptionUtil.wrapXuCloudException(AuthErrorCodeEnum.THIRD_PARTY_OAUTH2_FAIL, e);
        }
        AssertUtil.assertNotNull(oAuth2UserInfo, AuthErrorCodeEnum.THIRD_PARTY_OAUTH2_FAIL.info().newException());
        return oAuth2UserInfo;
    }

    private IOAuth2 select(ThirdPartyEnum thirdPartyEnum) {
        for (IOAuth2 IOAuth2 : IOAuth2s) {
            if (IOAuth2.support(thirdPartyEnum)) {
                return IOAuth2;
            }
        }
        return null;
    }
}
